import { useEffect, useState, useRef, useCallback, useLayoutEffect } from 'react';
import { Skeleton, App } from 'antd';
import loadable from '@loadable/component';
import $ from 'cash-dom';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import { setStore } from '@/reducers/common';
import { likeComment } from '@/service/comments';
import { ACCOUNT } from '@/config/url';
import styles from './index.module.scss';

const IconFont = loadable(() => import('@/components/IconFont'));
const CommentForm = loadable(() => import('./../CommentForm'), { fallback: <Skeleton.Input style={{padding:6}} active/> });

export default props => {
    const initState = () => ({
        replyOpen: false,
        like: false,
        likeNum: 0,
    });
    const [state, setState] = useState(initState);
    const { message } = App.useApp();
    const dispatch = useDispatch();
    const { dataSource={}, onlyShow=false, id, objectType } = props;
    const cInfo = props.dataSource || {};
    const isRoot = !Boolean(cInfo?.parentId);
    const container = useRef(null);
    const stateRef = useRef({});
    const navigate = useNavigate();

    // 跳转个人中心
    const toAccount = () => {
        if(!cInfo.fromMemberId) return;
        navigate(`${ACCOUNT}?uid=${cInfo.fromMemberId}`);
    };

    const reply = () => {
        const { replyOpen } = state;
        setState(o => ({...o, replyOpen: !replyOpen}));

        let t = setTimeout(() => {
            clearTimeout(t);

            if(!replyOpen) {
                window.addEventListener('click', listenFunc, false);
            }
        }, 0);
    };

    const report = () => {
        dispatch(setStore({ reportVisible: true, reportTarget: { ...cInfo, type: 'comment' } }));
    };

    const onOk = () => {
        setState(o => ({...o, replyOpen: false}));
        props.onOk();
    };

    const onCancel = () => {
        setState(o => ({...o, replyOpen: false}));
    };

    const handleLike = () => {
        message.destroy();
        const isCancel = !!state.like;
        likeComment({commentId: cInfo.id}).then(res => {
            if(OK_CODE === res?.code) {
                message.success(`${isCancel ? '取消' : ''}点赞成功`);
                setState(o => ({...o, like: !o.like, likeNum: isCancel ? o.likeNum-1 : o.likeNum+1}));
            }
        })
    };

    const listenFunc = useCallback((e) => {
        const target = $(e.target);
        if(!target.closest(container.current).length) {
            setState(o => ({...o, ...stateRef.current, replyOpen: false}));
            window.removeEventListener('click', listenFunc, false);
        }
    }, []);

    useEffect(() => {
        stateRef.current = state;
    }, [state]);
    useEffect(() => {
        setState(o => ({...o, like: cInfo.hasLiked, likeNum: cInfo?.likeNum||0}));
    }, [cInfo]);

    return (
        <div className={`${styles['container']} ${isRoot ? '' : styles['child']}`}>
            <div className={styles['avatar']} onClick={toAccount}>
                <img src={cInfo.fromAvatar ? `${cInfo.fromAvatar}?x-oss-process=image/resize,p_40` : ''} alt="" />
            </div>
            <div className={styles['content']}>
                <div className={styles['name']}>
                    {cInfo.fromNickName || cInfo.fromUserId}
                    {
                        isRoot || onlyShow ?
                            null
                            :
                            <><span>回复</span>{cInfo.toNickName || cInfo.toUserId}</>
                    }
                </div>
                <div className={styles['text']}>{cInfo.content || ''}</div>
                <div className={styles['footer']}>
                    <div className={styles['time']}>{cInfo.createTime||'--'}</div>
                    { onlyShow ? null : <div className={`${styles['reply']} ${state.replyOpen?styles['focus'] : ''}`} onClick={reply}>{state.replyOpen?'取消':''}回复</div> }
                    {/* <div className={styles['report']} onClick={report}>举报</div> */}
                </div>

                {
                    state.replyOpen ?
                        <div className={styles['form-container']} ref={container}>
                            <CommentForm
                                id={id}
                                objectType={objectType}
                                commentInfo={cInfo}
                                isReply={true}
                                onOk={onOk}
                                onCancel={onCancel}
                            />
                        </div>
                        :
                        null
                }
            </div>
            {
                true||onlyShow ?
                    null
                    :
                    <div className={`${styles['action']} ${state.like ? styles['active'] : ''}`} onClick={handleLike}>
                        <div className={styles['icon']}><IconFont name={state.like ? `icon-dianzanmian` : `icon-dianzan`}/></div>
                        {state.likeNum || 0}
                    </div>
            }
        </div>
    )
}
